<template>
  <div id="app" style="width: 100%;height: 600px">
    <SpectrumView ref="spectrumViewRef" />
    <div style="color: white;" />
    <div style="color: white;">
      状态：{{ status }}
    </div>
    <input
      v-model="dataUrl"
      type="text"
      placeholder="输入数据URL"
      style="width: 300px; margin-top: 20px;"
    >
    
    <button @click="wsConnection?.send(JSON.stringify({ messageType: 'fileUrl', url: dataUrl }))">
      发送数据URL
    </button>
    <button @click="wsConnection?.send(JSON.stringify({ messageType: 'start' }))">
      开始播放
    </button>
    <button @click="wsConnection?.send(JSON.stringify({ messageType: 'stop' }))">
      停止播放
    </button>


    <div style="color: white; margin-top: 20px;">
      显示设置
    </div>
    <div style="color: white;">
      显示模式：
      <select v-model="showMode" @change="setShowMode(showMode)">
        <option :value="1">
          频谱图
        </option>
        <option :value="3">
          瀑布图
        </option>
        <option :value="5">
          频谱+瀑布
        </option>
      </select>
      最大值保持：
      <input v-model="fftHeaps" type="checkbox" @change="setFftHeaps(fftHeaps)">
      <button @click="levelAdaptive();">
        频谱自适应
      </button>
    </div>


    <div style="color: white;margin-top: 20px;">
      配置：
    </div>
    <div style="color: white;">
      数据类型：
      <select v-model="dataType">
        <option :value="0">
          实信号
        </option>
        <option :value="1">
          复信号
        </option>
      </select>
      fft长度：
      <input v-model="fftLen" type="number">
      窗口类型：
      <select v-model="winType">
        <option :value="0">
          不加窗
        </option>
        <option :value="1">
          矩形窗
        </option>
        <option :value="2">
          三角形窗
        </option>
        <option :value="3">
          汉宁窗
        </option>
        <option :value="4">
          海明窗
        </option>
        <option :value="5">
          布莱克曼窗
        </option>
      </select>
      平滑：
      <input v-model="smooth" type="checkbox">
      平滑次数：
      <input v-model="smoothNum" type="number">
      更新间隔：
      <input v-model="interval" type="number"> ms
      <button @click="configParam">
        更新配置
      </button>
    </div>
  </div>
</template>


<script lang="ts" setup>
import SpectrumView from './components/spectrum-view.vue';
import { useWebSocket } from '@vueuse/core';
import type { UseWebSocketReturn } from '@vueuse/core';
import { onMounted, onUnmounted, ref } from 'vue';

const spectrumViewRef = ref<any>(null);
const wsUrl = ref('ws://127.0.0.1:22203'); // WebSocket 服务地址
let wsConnection: UseWebSocketReturn<any> | null = null;
// let start = performance.now();

const dataUrl = ref('D:/3678.wav');
const status = ref('等待连接...');
const showMode = ref(1);
const fftHeaps = ref(false);

const dataType = ref(0); // 0: 实信号, 1: 复信号
const fftLen = ref(4096);
const winType = ref(5);
const smooth = ref(true);
const smoothNum = ref(8);
const interval = ref(50);

// 处理 WebSocket 接收到的消息
const handleWebSocketMessage = async (_ws: WebSocket, event: MessageEvent) => {
  try {
    // 尝试将接收到的数据解析为 JSON 格式
    const data = JSON.parse(event.data);
    // console.log(data);
    if (spectrumViewRef.value) {
      // const start = performance.now();
      spectrumViewRef.value.appendFftData(data.data, 100, 200);
      spectrumViewRef.value.setFreqRange({ left: 100, right: 200 });
      // const end = performance.now();
      // console.log(`频谱数据更新时间间隔: ${end - start} ms,size: ${event.data.length/1024} KB`);
      // start = performance.now();
    } else {
      // console.warn(`没有找到 SpectrumView`);
    }
  } catch (error) {
    console.error('Error parsing message:', error);
  }
};

// 设置显示类型
const setShowMode = (mode: number) => {
  spectrumViewRef.value.setShowMode(mode);
};

// 设置是否fft最大值保持
const setFftHeaps = (value: boolean) => {
  spectrumViewRef.value.setFftHeaps(value);
};

// 频谱自适应
const levelAdaptive = () => {
  spectrumViewRef.value.levelAdaptive();
};

const configParam = () => {
  wsConnection?.send(JSON.stringify({messageType: 'config', dataType: dataType.value, fftLen: fftLen.value, winType: winType.value, smooth: smooth.value, smoothNum: smoothNum.value, interval: interval.value }));
};

onMounted(() => {
  wsConnection = useWebSocket(wsUrl.value, {
    autoReconnect: true,
    onMessage: handleWebSocketMessage,
    onError: () => {
      status.value = '连接异常，请检查 WebSocket 服务是否运行';
    },
    onConnected: () => {
      status.value = '连接成功';
    },
  });

});

onUnmounted(() => {
  wsConnection?.close();
});

</script>
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #0b0e11;
  margin-top: 60px;
}
</style>
